package com.time.workshop.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.time.workshop.API;
import com.time.workshop.R;
import com.time.workshop.SuperActivity;
import com.time.workshop.adapter.SelectAdapter;
import com.time.workshop.bean.KeShiName;
import com.time.workshop.bean.OrderType;
import com.time.workshop.bean.RequestOrder;
import com.time.workshop.injector.Injector;
import com.time.workshop.injector.V;
import com.time.workshop.utils.CommonUtils;
import com.time.workshop.utils.LaoBanDialog;
import com.time.workshop.utils.NewToast;
import com.time.workshop.utils.OnClickOKListener;

/**
 * 接送服务
 * 
 * @author wangfeng
 *
 */
public class JieSongActivity extends SuperActivity
{

	@V
	private TextView jiesong_order_timeTextView, jiesong_order_commitOrderTextView, jiesong_cartypeEditText;
	@V
	private Button jiesong_order_titlebar_left_btn;
	@V
	private EditText jiesong_order_nameEditText, jiesong_order_phoneEditText, jie_addressEditText, song_addressEditText, jiesong_order_remarksEditText;
	@V
	private RelativeLayout jiesong_cartype_Layout;

	private DatePicker datePicker;
	private TimePicker timePicker;
	private AlertDialog dialog;
	public Calendar time = Calendar.getInstance(Locale.CHINA);

	private String jiesongtime, name, phone, cartype, jieaddress, songaddress, remark;

	@Override
	protected void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		setContentView(R.layout.activity_jiesong);
		setView();
		lp = getWindow().getAttributes(); // 设置popupWindow弹出后背景的阴影
	}

	private void setView()
	{
		Injector.getInstance().inject(this);
		jiesong_order_titlebar_left_btn.setOnClickListener(this);
		jiesong_order_timeTextView.setOnClickListener(this);
		jiesong_order_commitOrderTextView.setOnClickListener(this);
		jiesong_cartype_Layout.setOnClickListener(this);
	}

	@Override
	public void onClick(View view)
	{
		super.onClick(view);
		switch (view.getId())
		{
		case R.id.jiesong_order_titlebar_left_btn:
			back();
			break;
		case R.id.jiesong_order_timeTextView:
			dateTimePickerDialog();
			break;
		case R.id.jiesong_order_commitOrderTextView:
			submit();
			break;
		case R.id.jiesong_cartype_Layout:
			requestCarType();
			break;

		default:
			break;
		}
	}

	private List<KeShiName> lists = new ArrayList<KeShiName>();

	private void requestCarType()
	{
		HttpUtils httpUtils = new HttpUtils();
		lists.clear();
		httpUtils.send(HttpMethod.GET, API.car_type, new RequestCallBack<String>()
		{

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				Gson gson = new Gson();
				lists = gson.fromJson(responseInfo.result, new TypeToken<List<KeShiName>>()
				{
				}.getType());
				chooseCarTypePopu();
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{
			}
		});
	}

	private PopupWindow popuCar;
	private WindowManager.LayoutParams lp;

	private void chooseCarTypePopu()
	{
		LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
		View selectView = inflater.inflate(R.layout.pop_selector_keshi, null);
		ListView listViewZhuanJia = (ListView) selectView.findViewById(R.id.list_one);
		int height = lists.size();
		if (lists.size() > 5)
		{
			height = 5;
			LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams) listViewZhuanJia.getLayoutParams();
			params.height = jiesong_cartype_Layout.getHeight() * height;
			listViewZhuanJia.setLayoutParams(params);
		}
		final SelectAdapter<KeShiName> zhuanjiaadapter = new SelectAdapter<KeShiName>(this, lists);
		listViewZhuanJia.setAdapter(zhuanjiaadapter);
		listViewZhuanJia.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				jiesong_cartypeEditText.setText(lists.get(position).getNAME());
				cartype = lists.get(position).getID();
				zhuanjiaadapter.notifyDataSetChanged();
				popuCar.dismiss();
			}
		});

		popuCar = new PopupWindow(selectView);
		popuCar.setWidth(jiesong_cartype_Layout.getWidth());
		popuCar.setHeight(LayoutParams.WRAP_CONTENT);
		popuCar.setOutsideTouchable(true);
		popuCar.setFocusable(true);
		lp.alpha = 0.4f;
		getWindow().setAttributes(lp);
		popuCar.setOnDismissListener(new OnDismissListener()
		{
			@Override
			public void onDismiss()
			{
				lp.alpha = 1.0f;
				getWindow().setAttributes(lp);
			}
		});
		popuCar.setBackgroundDrawable(new ColorDrawable());
		int[] location = new int[2];
		jiesong_cartype_Layout.getLocationOnScreen(location);
		popuCar.setAnimationStyle(R.style.TypeSelAnimationFadeBottom);
		popuCar.showAtLocation(jiesong_cartype_Layout, Gravity.NO_GRAVITY, location[0], location[1] - jiesong_cartype_Layout.getHeight() * height);
	}

	private void submit()
	{
		jiesongtime = jiesong_order_timeTextView.getText().toString().trim();
		name = jiesong_order_nameEditText.getText().toString().trim();
		phone = jiesong_order_phoneEditText.getText().toString().trim();
		jieaddress = jie_addressEditText.getText().toString().trim();
		songaddress = song_addressEditText.getText().toString().trim();
		remark = jiesong_order_remarksEditText.getText().toString().trim();
		if ("".equals(CommonUtils.isNull(jiesongtime)))
		{
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.toast_run_time));
			return;
		}
		if ("".equals(CommonUtils.isNull(name)))
		{
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.toast_name));
			return;
		}
		if (!CommonUtils.isMobile(phone))
		{
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.toast_phone));
			return;
		}
		if ("".equals(CommonUtils.isNull(cartype)))
		{
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.toast_jiesong_cartype));
			return;
		}
		if ("".equals(CommonUtils.isNull(jieaddress)))
		{
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.toast_jie_address));
			return;
		}
		if ("".equals(CommonUtils.isNull(songaddress)))
		{
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.toast_song_address));
			return;
		}
		showConfirmDialog();
	}

	private LaoBanDialog dlg;

	/**
	 * 显示 Dailog
	 */
	private void showConfirmDialog()
	{

		dlg = new LaoBanDialog(JieSongActivity.this);
		if (dlg.isShowing())
		{
			dlg.dismiss();
			return;
		}
		dlg.onCreate();
		dlg.setOnClickOK(new OnClickOKListener()
		{

			@Override
			public void setOnClickOK()
			{
				// Intent in = new
				// Intent(CustomMadeActivity.this,ConfirmOrderActivity.class);
				// in.putExtra("name", name);
				// in.putExtra("content", content);
				// in.putExtra("phone", phone);
				// startActivity(in, true);
				// dlg.dismiss();
				dlg.dismiss();
				RequestOrder requestOrder = new RequestOrder();
				requestOrder.ORDER_TYPE = OrderType.LCWDD.toString();
				requestOrder.reservation_time = jiesongtime;
				requestOrder.contactor_person = name;
				requestOrder.contactor_phone = phone;
				requestOrder.remark = remark;
				requestOrder.CAR_TYPE = cartype;
				requestOrder.SEND_ADDRESS = songaddress;
				requestOrder.contactor_address = jieaddress;
				API.submitOrder(requestOrder, JieSongActivity.this);
			}
		});
	}

	// 选择时间
	private AlertDialog dateTimePickerDialog()
	{
		LinearLayout dateTimeLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.date_time_picker, null);
		datePicker = (DatePicker) dateTimeLayout.findViewById(R.id.DatePicker);
		timePicker = (TimePicker) dateTimeLayout.findViewById(R.id.TimePicker);
		timePicker.setIs24HourView(true);

		OnTimeChangedListener timeListener = new OnTimeChangedListener()
		{
			@Override
			public void onTimeChanged(TimePicker view, int hourOfDay, int minute)
			{
				time.set(Calendar.HOUR_OF_DAY, hourOfDay);
				time.set(Calendar.MINUTE, minute);

			}
		};

		timePicker.setOnTimeChangedListener(timeListener);
		OnDateChangedListener dateListener = new OnDateChangedListener()
		{

			@Override
			public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
			{
				time.set(Calendar.YEAR, year);
				time.set(Calendar.MONTH, monthOfYear);
				time.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			}
		};

		datePicker.init(time.get(Calendar.YEAR), time.get(Calendar.MONTH), time.get(Calendar.DAY_OF_MONTH), dateListener);
		timePicker.setCurrentHour(time.get(Calendar.HOUR_OF_DAY));
		timePicker.setCurrentMinute(time.get(Calendar.MINUTE));

		dialog = new AlertDialog.Builder(this).setTitle("设置日期时间").setView(dateTimeLayout).setPositiveButton("确定", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{

				time.set(Calendar.YEAR, datePicker.getYear());
				time.set(Calendar.MONTH, datePicker.getMonth());
				time.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
				time.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
				time.set(Calendar.MINUTE, timePicker.getCurrentMinute());
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				jiesong_order_timeTextView.setText(format.format(time.getTime()));
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{

			}
		}).show();
		return dialog;
	}

}
